import { createSlice } from "@reduxjs/toolkit";
import { useSelector } from 'react-redux';

// 类型别名  用type关键字定义类型别名

export type TPanes = {
  title: string,
  key:string,
  closable:boolean,
}

export type TPage = {
  current: number,
  pageSize:number,
  total:number
}


type TCommonState = {
  panes:TPanes[],
  pageInfo:TPage,
  loading:boolean
}




// 在外面写初始状态
const initialState:TCommonState = {
  panes:[
    {
      title:'主页',
      key:'/',
      closable:false
    }
  ],
  pageInfo:{
    current:1,
    pageSize:1,
    total:1
  },
  loading:false
}

const commonSlice = createSlice({
  name:'common',
  initialState,
  reducers:{
    // 添加panes
    addPanes(state,{payload}){
      const info:TPanes = state.panes.find((p:TPanes)=>p.key === payload.key) as TPanes //类型断言 用as关键字  指定具体的类型
      // console.log(payload);// 路径
      if(!info){
        state.panes.push(payload)
      }
    },
    // 删除panes
    delPandes(state,{payload}){
      // console.log(payload);
      state.panes.splice(payload,1)
    },
    // 分页处理
    changePageInfo(state,{payload}){
      // console.log(state.pageInfo);
      // console.log(payload); // 一个对象 当前页码 和 本页数量
      state.pageInfo = payload  // 改变本页的当前状态
    },
    // 处理正在加载中
    changeLoading(state,{payload}){
      state.loading = payload
    },


    changeTitleByKey(state,{payload}){
      // payload= {key,title}
      const info:TPanes = state.panes.find(v=>v.key === payload.key) as TPanes;
      info.title = payload.title;
    },
    delPanesByKey(state,{payload}){
      const index = state.panes.findIndex(v=>v.key === payload);
      state.panes.splice(index,1);
    },


  }
})

// 导出actions
export const {addPanes,delPandes,changePageInfo,changeLoading,changeTitleByKey,delPanesByKey} = commonSlice.actions
// 导出common的状态
export const useSelectorCommon = ()=> useSelector((state:any)=>state.common)
export default commonSlice.reducer